package com.baymax.springboot.cli.generator;

import com.baymax.springboot.cli.generator.component.JavaCodeTemplateRender;
import com.baymax.springboot.cli.generator.component.entity.ColumnConstTemplateRender;
import com.baymax.springboot.cli.generator.component.meta.TableMeta;
import com.jfinal.template.Engine;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author xiao.hu
 */
public class CodeGenerator {
    /**
     * 以CodePath所在的包为主输出目录
     */
    public static final String outputRootPackage = CodeGenerator.class.getPackage().getName() + ".output";
    public static final String targetClassesPath = CodeGenerator.class.getClassLoader().getResource("").getPath();
    public static final String srcPath = targetClassesPath + "../../src";
    public static final String mavenMainJavaPath = srcPath + "/main/java/";

    private static List<JavaCodeTemplateRender> renderList = new ArrayList<> ();
    static {
        renderList.add(new ColumnConstTemplateRender(mavenMainJavaPath, outputRootPackage));
    }

    public static List<TableMeta> tableMetaList = new ArrayList<>();

    public static void generateColumnConst(List<TableMeta> tableMetaList) {
        Engine engine = Engine.create("ocoder");
        for(JavaCodeTemplateRender render : renderList) {
            render.render(engine, tableMetaList);
        }
    }

    public static void main(String[] args) throws Exception{
        CodeGenerator app = new CodeGenerator();

        System.out.println(app.getClass().getResource("/").getPath());
        app.generator();
        System.out.println(System.getProperty("user.dir"));

        generateColumnConst(tableMetaList);
    }

    public void generator() throws Exception{

        List<String> warnings = new ArrayList<String>();

        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("mybatis-generator/generatorConfig.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(resourceAsStream);
        DefaultShellCallback callback = new DefaultShellCallback(true);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);

        for(String warning:warnings){
            System.out.println(warning);
        }
    }
}
